<template>
	<div>
		<el-form
		style="margin-top:20px;"
		    :model="ruleForm"
		    ref="ruleForm"
		    :rules="rules"
		    :label-position="labelPosition"
		    label-width="120px"
		    class="demo-ruleForm"
		>
		    <el-row class="container">
				<el-page-header @back="goback" content="新增产出物">
				</el-page-header>
		        <el-col :span="12" style="margin-top:20px;">
		            <el-form-item label="产出物类型：" prop="type">
		                <template>
		                    <el-select
		                        v-model="ruleForm.type"
		                        style="width:300px"
								value-key="id"
		                        placeholder="请选择">
		                        <el-option
		                            v-for="item in typeList"
		                            :key="item.id"
		                            :label="item.name"
		                            :value="item.name"
		                        ></el-option>
		                    </el-select>
		                </template>
		            </el-form-item>
					<el-form-item label="产出物批号：" prop="batch">
					    <el-input placeholder="请输入" v-model="ruleForm.batch" style="width: 300px">
					        <template slot="append">
								<el-button @click="addBatch">自动生成</el-button>
					        </template>
					    </el-input>
					</el-form-item>

					<el-form-item label="产出负责人：" prop="name">
						<template>
							<el-select
								v-model="ruleForm.name"
								style="width:300px"
								placeholder="请选择">
								<el-option
									v-for="item in userList"
									:key="item.id"
									:label="item.name"
									:value="item.name"
								></el-option>
							</el-select>
						</template>
					</el-form-item>
		        </el-col>
		        <el-col :span="10" style="margin-top:20px;" prop="cropName">
					<el-form-item label="产出物名称：" v-model="ruleForm.cropName">
						<el-input style="width:300px;" ></el-input>
					</el-form-item>
					<el-form-item label="产出日期：" prop="outTime">
					    <el-date-picker
					        v-model="ruleForm.outTime"
					        type="date"
					        value-format="yyyy-MM-dd"
					        placeholder="请选择"
					        style="width:300px"
					    ></el-date-picker>
					</el-form-item>
					<el-form-item label="数量：" prop="number">
					    <el-input placeholder="请输入" v-model="ruleForm.number" style="width: 300px">
					        <template slot="append">
					            <el-select
					                v-model="ruleForm.units"
					                placeholder="单位"
					                style="width:80px !important">
					                <el-option
					                    v-for="item in unitsList"
					                    :key="item.id"
					                    :label="item.name"
					                    :value="item.name"
					                ></el-option>
					            </el-select>
					        </template>
					    </el-input>
					</el-form-item>
		        </el-col>
		    </el-row>
			<el-row class="container" style="margin:20px 0px 30px 0px;">
				<h3>品种信息</h3>
				<el-form-item label="编号类型：" style="margin-top:20px;">
                    <el-radio-group v-model="type">
                        <!-- <el-radio label="耳标" border>耳标</el-radio> -->
                        <el-radio label="RFID" border>RFID</el-radio>
                        <el-radio label="养殖批号" border>养殖批号</el-radio>
                    </el-radio-group>
				</el-form-item>
				<el-form-item label="RFID：" v-if="type == 'RFID'">
					<el-input placeholder="请输入" v-model="param" style="width: 300px">
						<template slot="append">
							<el-button @click="getBreedDetail">导入</el-button>
						</template>
					</el-input>
					<el-upload
						class="upload-demo"
						ref="upload"
						accept=".txt"
						action="https://jsonplaceholder.typicode.com/posts/"
						:before-upload="beforeUpload"
						:default-file-list="this.fileList"
					  >
					  <el-button slot="trigger" size="small" type="primary">批量导入</el-button>
					</el-upload>
					<!-- <el-button>模板下载</el-button> -->
				</el-form-item>
				<el-form-item label="养殖批号" v-if="type == '养殖批号'">
					<el-select
						v-model="param"
						@change="addParent1"
						value-key="id"
						style="width:300px"
						placeholder="请选择"
					>
						<el-option
							v-for="item in batchList"
							:key="item.id"
							:label="item.batch"
							:value="item.batch">
						</el-option>
					</el-select>
				</el-form-item>
				<el-table
					:data="tableData"
					border
					style="margin-top:20px;"
					ref="multipleTable"
					header-cell-class-name="table-header">
					<el-table-column prop="seedName" sortable label="品种名称"></el-table-column>
					<el-table-column prop="batch" sortable label="养殖批号"></el-table-column>
					<el-table-column prop="type" sortable label="编号类型"></el-table-column>
					<el-table-column prop="code" sortable label="编号"></el-table-column>
					<el-table-column prop="sex" sortable label="性别">
						<template slot-scope="scope">
							<el-select v-model="scope.row.sex" placeholder="请选择">
							    <el-option
							      v-for="item in sexlist"
							      :key="item.value"
							      :label="item.value"
							      :value="item.value">
							    </el-option>
							 </el-select>
						</template>
					</el-table-column>
					<el-table-column prop="buyTime" sortable label="最近产出日期"></el-table-column>
					<el-table-column prop="buyTime" sortable label="最近产出类型"></el-table-column>
					<el-table-column prop="buyTime" label="操作" width="150" align="center">
						<template slot-scope="scope">
							<el-button
								type="text"
								style="color: red;"
								@click="handleDelete(scope.$index, scope.row)"
							>删除</el-button>
						</template>
					</el-table-column>
				</el-table>
				<!-- <el-pagination
					layout="total, prev, pager, next, jumper"
					:page-size="pagesize"
					:current-page.sync="currentPage"
					:total="total"
					@current-change="handleCurrentChange"
					style="margin-top:20px"
				></el-pagination> -->
			</el-row>
		    <el-form-item class="footerFixed" label-width="0px">
		        <el-button type="primary" @click="submitrule('ruleForm')">提交</el-button>
		        <el-button @click="goback">取消</el-button>
		    </el-form-item>
		</el-form>
	</div>
</template>

<script>
import { user_findByAll,unit_findByList,model_crop_loadbind } from '@/request/api';
import { crop_getBreedDetail,crop_save,crop_findById,crop_findByDetailList,breed_findBatchSelect } from '@/request/breedApi';
	export default{
		data(){
			return{
				batchList:[],
				fileList:"",
				tableData:[],
				radio1:'耳标',
				labelPosition:'right',
				ruleForm:{
				batch:''
				},
				rules:{
					type: [{ required: true, message: '不能为空', trigger: 'change' }],
					batch: [{ required: true, message: '不能为空', trigger: 'change' }],
					name: [{ required: true, message: '不能为空', trigger: 'change' }],
					cropName: [{ required: true, message: '不能为空', trigger: 'change' }],
					outTime: [{ required: true, message: '不能为空', trigger: 'change' }],
					number: [{ required: true, message: '不能为空', trigger: 'change' }],
				},
				typeList:[],
				userList:[],
				unitsList:[],
				currentPage:1,
			    param:'',
			    type:'耳标',
				total:0,
				pagesize:10,
				sexlist:[
					{value:"雌"},
					{value:"雄"}
				],
			}
		},
		beforeCreate() {
			// 读取文件
			FileReader.prototype.reading = function ({encode} = pms) {
				let bytes = new Uint8Array(this.result);    //无符号整型数组
				let text = new TextDecoder(encode || 'UTF-8').decode(bytes);
				return text;
			};
			/* 重写readAsBinaryString函数 */
			FileReader.prototype.readAsBinaryString = function (f) {
				if (!this.onload)       //如果this未重写onload函数，则创建一个公共处理方式
					this.onload = e => {  //在this.onload函数中，完成公共处理
						let rs = this.reading();
						// console.log(rs);
					};
				this.readAsArrayBuffer(f);  //内部会回调this.onload方法
			};
		},
		mounted() {
			this.init();
			this.init1()
			this.id = this.$route.query.id
			if(this.id != undefined){
				this.getdetails()
			}
		},
		methods:{
			getdetails(){
				const _this = this;
				// this.id = _this.$route.query.id
				crop_findById(this.id).then((res) => {
				  if (res.code == 200) {
				  this.ruleForm = res.data;
				 }
				});

				 var params = {
				    query: this.searchName,
				    page: this.currentPage,
				    breedCropId:this.id
				 };
				crop_findByDetailList(params).then((res) => {
				  if (res.code == 200) {
				       this.tableData = res.rows;
				       this.total = res.total;
				   }
				});
			},
			beforeUpload(file){
				this.fileList = [file]
				this.read(file);
				return false
			},
            addBatch() {
                var d = new Date();
                var curr_date = d.getDate();
                var curr_month = d.getMonth() + 1;
                var curr_year = d.getFullYear();
                String(curr_month).length < 2 ? (curr_month = "0" + curr_month): curr_month;
                String(curr_date).length < 2 ? (curr_date = "0" + curr_date): curr_date;
                var yyyyMMdd = curr_year + "" + curr_month +""+ curr_date;
                this.ruleForm.batch = yyyyMMdd + Math.ceil(Math.random()*10000);
            },
			read(f) {
				let rd = new FileReader();
				rd.onload = e => {
				//this.readAsArrayBuffer函数内，会回调this.onload函数。在这里处理结果
					let cont = rd.reading({encode: 'GBK'});
					let  formerData = this.textData;

					if(formerData == "" || formerData == null || formerData == undefined){
						this.textData = cont
					}else{
						this.textData = formerData + cont;
					}
					this.textData = this.textData.split("\r\n")

					var d=new Date();
					var year=d.getFullYear();
					var month=change(d.getMonth()+1);
					var day=change(d.getDate());
					var hour=change(d.getHours());
					var minute=change(d.getMinutes());
					var second=change(d.getSeconds());
					function change(t){
						if(t<10){
						return "0"+t;
						}else{
						return t;
						}
					}

					var time=year+'-'+month+'-'+day+' '+hour+':'+minute+':'+second;
					if(this.type == "" || this.type == null ||  this.type == undefined){
						this.$notify({
							title: '提示',
							message: '请选择编号类型后重新导入',
							type: 'info',
							duration:1000
						});
					}else{
						// console.log(this.textData)
						var params = {
						   type: this.type,
						   param: this.textData
						};
						crop_getBreedDetail(params).then((res) => {
						   if (res.code == 200) {
						       this.tableData=res.data;
						    }
						});
						// for(var i=0;i<this.textData.length;i++){
						// 	console.log(this.textData[i])
						// 	var params = {
						// 		"time":time,
						// 		"type":this.ruleForm.type,
						// 		"code":this.textData[i],
						// 		"sex":""
						// 	}
						// 	this.tableData.push(params);
						// }
					}
					this.textData = ""
				};
				rd.readAsBinaryString(f);
			},

			init1(){
        model_crop_loadbind("").then((res)=>{
					this.typeList = res.data
				})
			},
            // 页面一进来加载
            init() {
             unit_findByList("").then((res) => {
                  if (res.code == 200) {
                    this.unitsList = res.data;
                  }
             });
			 breed_findBatchSelect("").then((res)=>{
			 	this.batchList = res.data
			 })
              user_findByAll("").then((res) => {
                if (res.code == 200) {
                        this.userList = res.data;
                    }
                   });
            },

		    getBreedDetail(){
				let data = []
				data.push(this.param)
				var params = {
					type: this.type,
					param:data
				};
				crop_getBreedDetail(params).then((res) => {
					if (res.code == 200) {
						this.tableData= this.tableData.concat(res.data);
					 }
					 this.param = ""
				});
		    },
			addParent1(){
				let data = []
				data.push(this.param)
				var params = {
					type:this.type,
					param:data
				}
				crop_getBreedDetail(params).then((res) => {
					if (res.code == 200) {
						this.tableData= this.tableData.concat(res.data);
					 }
					 this.param = ""
				});
			},
			// 返回上一页
			goback(){
				this.$router.go(-1)
			},
			// 删除
			handleDelete(index,row){
				this.tableData.splice(index,1)
			},

			handleCurrentChange(val) {
			    this.currentPage = val;

			},

            // 提交
            submitrule(){
				this.$refs[formName].validate((valid) => {
					if (valid) {
						if(this.ruleForm.units == "" || this.ruleForm.units == undefined){
							this.$notify({
								title: '提示',
								message: '数量单位不能为空',
								type: 'info'
							});
							return false
						}
						this.$confirm('请仔细核对所填信息，提交后不能修改！', '提示', {
							confirmButtonText: '确定',
							cancelButtonText: '取消',
							type: 'warning'
						}).then(() => {
							this.ruleForm.breedCropDetails=this.tableData;
							crop_save(this.ruleForm).then((res) => {
								if (res.code == 200) {
									this.$router.go(-1)
								}
							 });
						})
					}else{
						return false
					}
				})
            }
		}
	}
</script>

<style scoped>
	.el-pagination {
	    text-align: center;
	}
	.upload-demo{
		display:inline-block;
		margin-left:20px;
	}

	/deep/.el-upload--text{
		width:80px;
		height:35px;
	}

</style>
